#include "Socket.h"

Socket::Socket()
    : sockfd_(-1)
{
}

Socket::Socket(socket_t sockfd)
    : sockfd_(sockfd)
{
}

bool Socket::getLocalSockName(std::string& ip, uint16_t& port)
{
    sockaddr_in addr;
    SockLen len = sizeof(addr);
    if (::getsockname(sockfd_, (sockaddr*)&addr, &len) != 0) {
        return false;
    }
    char buf[64] = { 0 };
    if(!::inet_ntop(AF_INET, &addr.sin_addr.s_addr, buf, sizeof(buf))){
        perror("inet_ntop");
        return false;
    }
    ip = buf;   
    port = ::ntohs(addr.sin_port);
    return true;
}

bool Socket::getPeerSockName(std::string& ip, uint16_t& port)
{
    sockaddr_in addr;
    SockLen len = sizeof(addr);
    if (::getpeername(sockfd_, (sockaddr*)&addr, &len) != 0) {
        return false;
    }
    char buf[64] = { 0 };
    if (!::inet_ntop(AF_INET, &addr.sin_addr.s_addr, buf, sizeof(buf))) {
        perror("inet_ntop");
        return false;
    }
    ip = buf;
    port = ::ntohs(addr.sin_port);
    return true;
}

bool Socket::shutdown()
{
    return SockOpt::shutdown(sockfd_) == 0;
}

bool Socket::close()
{
    return SockOpt::close(sockfd_) == 0;
}

Socket::~Socket()
{
    if (sockfd_ != -1)
    {
        SockOpt::shutdown(sockfd_);
        //SockOpt::close(sockfd_);
    }
}